package com.yonyougov.cruxtestcase.component.sm;

import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * SmClient:上下文取值
 */
@Component
public class SmClient {
//    private final ZWCDInvoke zwcdInvoke;
    private final RestTemplate restTemplate;

    public SmClient(RestTemplate restTemplate/*, ZWCDInvoke zwcdInvoke*/) {
        this.restTemplate = restTemplate;
//        this.zwcdInvoke = zwcdInvoke;
    }

    /**
     *设置用户上下文
     * @param token 凭证
     * @param param 入参
     * @return boolean
     */
    public boolean fillValue(String baseUrl, String token, Map<String, String> param){
//        String baseUrl = zwcdInvoke.getBaseUrl(envName);
        HttpHeaders headers=new HttpHeaders();
        headers.set("Authorization","Bearer " + token);
        HttpEntity<Map<String,String>> entity = new HttpEntity<>(param,headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(baseUrl + "/crux-sm/api/usercontext/value", HttpMethod.POST, entity, String.class);
        if(responseEntity.getStatusCode() == HttpStatus.OK){
            return true;
        }
        return false;
    }

    /**
     *获取用户上下文key对应的初始值
     * @param token 凭证
     * @param keyName 上下文的key
     * @return Object 上下文的值
     */
    public Object contextValue(String baseUrl, String token,String keyName){
//        String baseUrl = zwcdInvoke.getBaseUrl(envName);
        HttpHeaders headers=new HttpHeaders();
        headers.set("Authorization","Bearer " + token);
        HttpEntity<String> entity = new HttpEntity<>(null,headers);
        ResponseEntity<Object> responseEntity = restTemplate.exchange(baseUrl + "/crux-sm/api/usercontext/value?keyname="+keyName, HttpMethod.GET, entity, Object.class);
        if(responseEntity.getStatusCode() == HttpStatus.OK){
            return responseEntity.getBody();
        }
        return null;
    }
}
